package com.example.netty.service.impl;

import com.example.netty.server.tcp.TcpServer;
import com.example.netty.service.CallBack;
import com.example.netty.service.ServerService;
import io.netty.channel.ChannelHandlerContext;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;


@Service
public class ServerServiceImpl implements ServerService {

    private final static Logger logger = LoggerFactory.getLogger(ServerServiceImpl.class);


    @Override
    public void creat() throws UnknownHostException {
        String ip = InetAddress.getLocalHost().getHostAddress();
        int initPort = 4000;
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new TcpServer(ip, initPort + i, "UTF-8", 6, new CallBack() {
                @Override
                public void response(ChannelHandlerContext ctx, Object msg) throws Exception {
                    logger.info("服务端【{}】接收到消息{}", ctx.channel().id(), msg.toString());
                    String response = String.format("服务端%d返回消息：服务端%d已接收到消息！", finalI, finalI);
                    ctx.channel().writeAndFlush(response);
                }
            });
        }
    }

    @Override
    public void downLoad(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String filePath = "/Users/dava-j/Documents/编辑1.zip";
        String userAgent = request.getHeader("User-Agent");
        String formFileName = "员工表.zip";
        // 针对IE或者以IE为内核的浏览器：
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            formFileName = new String(formFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", formFileName));
        response.setContentType("application/form-download");
        response.setCharacterEncoding("UTF-8");
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(filePath);
            os = response.getOutputStream();
            IOUtils.copyLarge(fis, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                IOUtils.closeQuietly(os);
            }
            if (fis != null) {
                IOUtils.closeQuietly(fis);
            }
        }


    }


}

